<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import { useAuthStore } from '../stores/auth';
import { createCourse } from '../api/demo';

const authStore = useAuthStore();
const router = useRouter();

const formRef = ref();
const loading = ref(false);

const form = reactive({
  title: '',
  body: '',
  teachername: '',
  categoryText: '',
  picPaths: '',
  startTime: '',
  endTime: '',
});

const rules = {
  title: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
  body: [{ required: true, message: '请输入课程简介', trigger: 'blur' }],
  teachername: [{ required: true, message: '请输入任课老师姓名', trigger: 'blur' }],
};

const toTimestamp = (value) => {
  if (!value) return null;
  const date = dayjs(value);
  return date.isValid() ? date.valueOf() : null;
};

const handleSubmit = () => {
  if (!formRef.value) return;
  formRef.value.validate(async (valid) => {
    if (!valid) return;
    try {
      loading.value = true;
      const payload = {
        title: form.title,
        body: form.body,
        teachername: form.teachername,
        picPaths: form.picPaths,
        userid: authStore.user?.id,
        categoryid: form.categoryText || null,
        startTime: toTimestamp(form.startTime),
        endTime: toTimestamp(form.endTime),
      };
      const result = await createCourse(payload);
      ElMessage.success('课程发布成功');
      if (result?.id) {
        router.push({ name: 'course-detail', params: { id: result.id } });
      }
      handleReset();
    } catch (error) {
      ElMessage.error(error?.message || '发布课程失败，请稍后重试');
    } finally {
      loading.value = false;
    }
  });
};

const handleReset = () => {
  if (!formRef.value) return;
  formRef.value.resetFields();
  form.categoryText = '';
  form.picPaths = '';
  form.startTime = '';
  form.endTime = '';
};
</script>

<template>
  <div class="page-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <div>
            <h2>发布新课程</h2>
            <p>填写课程基本信息，类别当前支持自由输入，课程时间可选填。</p>
          </div>
        </div>
      </template>
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px" size="large">
        <el-form-item label="课程名称" prop="title">
          <el-input v-model="form.title" maxlength="100" show-word-limit placeholder="请输入课程名称" />
        </el-form-item>
        <el-form-item label="课程简介" prop="body">
          <el-input
            v-model="form.body"
            type="textarea"
            :rows="4"
            maxlength="1000"
            show-word-limit
            placeholder="请描述课程目标、教学内容等关键信息"
          />
        </el-form-item>
        <el-form-item label="任课教师" prop="teachername">
          <el-input v-model="form.teachername" placeholder="请输入教师姓名" />
        </el-form-item>
        <el-form-item label="课程类别">
          <el-input
            v-model="form.categoryText"
            placeholder="可直接输入课程类别名称，留空视为未分类"
            clearable
          />
        </el-form-item>
        <el-form-item label="课程封面">
          <el-input v-model="form.picPaths" placeholder="可填写课程封面图片URL，多个URL使用逗号分隔" />
        </el-form-item>
        <el-form-item label="开始时间">
          <el-date-picker
            v-model="form.startTime"
            type="datetime"
            placeholder="可选填开课时间"
            format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item label="结束时间">
          <el-date-picker
            v-model="form.endTime"
            type="datetime"
            placeholder="可选填结课时间"
            format="YYYY-MM-DD HH:mm"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="loading" @click="handleSubmit">提交发布</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped>
.page-container {
  max-width: 900px;
  margin: 0 auto;
}

.card-header h2 {
  font-size: 24px;
  margin-bottom: 4px;
}

.card-header p {
  color: #666;
}
</style>
